﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace HttpCrawler.Engine
{
    public class CssHttpCrawlerContentProcessor : IHttpCrawlerContentProcessor
    {
        public bool CanProcess(HttpCrawlerContent content)
        {
            if (content == null)
            {
                return false;
            }

            return content.IsCss();
        }

        public IEnumerable<string> Process(HttpCrawlerContent content)
        {
            if (content != null)
            {
                var css = content.Text;

                var matches = _CssUrlRegex.Matches(css);

                if (matches != null)
                {
                    var urls = matches.Cast<Match>().Select(m => UnescapeCssLiteral(m.Groups[1].Value)).ToArray();

                    return urls;
                }
            }

            return null;
        }

        /// <summary>
        /// Matches CSS Urls in the following format: 
        /// url('http://blah.com/my.css')
        /// </summary>
        private static readonly Regex _CssUrlRegex = new Regex(@"url\((?:'|""|)(.*?)(?:'|""|)(?<!\\)\)", RegexOptions.Compiled);

        /// <summary>
        /// Matches the following escape sequences: 
        /// \( \) \, \' \"
        /// </summary>
        private static readonly Regex _CssLiteralEscapeRegex = new Regex(@"(\\)(""|'|,|\(|\))", RegexOptions.Compiled);

        protected static string UnescapeCssLiteral(string input)
        {
            return _CssLiteralEscapeRegex.Replace(input, "$2");
        }
    }
}
